﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace CarPark.Helper
{
    public class SerialPortHelper
    {
        private byte[] cmd_open;
        private byte[] cmd_close;
        public SerialPortHelper()
        {
            cmd_open = new byte[4];
            cmd_close = new byte[4];
            cmd_open[0] = 0xFD; //0b11111101
            cmd_open[1] = 0x00;
            cmd_open[2] = 0x00;
            cmd_open[3] = 0x00;
            cmd_close[0] = 0xFE; //0b11111110
            cmd_close[1] = 0x00;
            cmd_close[2] = 0x00;
            cmd_close[3] = 0x00;
        }

        public void OpenFence(SerialPort port)
        {
            if (port.IsOpen)
                port.Write(cmd_open, 0, 4);
        }

        public void CloseFence(SerialPort port)
        {
            if (port.IsOpen)
                port.Write(cmd_close, 0, 4);
        }

        /// <summary>
        /// 解读数据包，分析卡号，卡号约定范围是1000000-1009999
        /// </summary>
        /// <param name="package"></param>
        /// <returns></returns>
        public int GetCardID(byte[] package)
        {
            int data = (package[1] >> 4) * 1000 + (package[1] & 0x0F) * 100 + (package[2] >> 4) * 10 + (package[2] & 0x0F);
            return data + 1000000; 
        }




    }


/*备份
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                if (serialPort1.BytesToRead > 3)
                {
                    serialPort1.Read(rbuff1, 0, 4);
                    if (rbuff1[0] == 0xFC) //有车开入或开出
                    {
                        timer1.Enabled = false;
                        string cdid = sph.GetCardID(rbuff1).ToString();
                        if (MessageBox.Show(mcp.GetCurrentUserInfoByString(ref cdid, ""), "出入确认", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            txtInOrOutCardID.Text = cdid;
                            btnIn_Click(null, null);
                        }
                    }
                    timer1.Enabled = true;
                }
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                if (serialPort2.BytesToRead > 3)
                {
                    serialPort2.Read(rbuff2, 0, 4);
                    if (rbuff2[0] == 0xFF) //车辆已通过护栏
                    {
                        timer2.Enabled = false;
                        sph.CloseFence(serialPort2);
                    }
                    timer2.Enabled = true;
                }
            }
        } 
 */

}
